package school.xauat.现代密码学.对称加密;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author ：zsy
 * @date ：Created 2021/6/17 9:51
 * @description：Des加密
 */
public class DesDemo {
    public static void main(String[] args) throws Exception {
        String input = "计算机网络";
        //加密密钥
        String key = "12345678";
        //加密模式
        //String transformation = "DES/ECB/PKCS5Padding";
        String transformation = "DES/CBC/PKCS5Padding";
        //加密算法
        String algorithm = "DES";
        String encryptDES = encryptDES(input, key, transformation, algorithm);
        System.out.println("加密后：" + encryptDES);
        String decryptDES = decryptDES(encryptDES, key, transformation , algorithm);
        System.out.println("解密后：" + decryptDES);
    }

    private static String encryptDES(String input, String key, String transformation, String algorithm) throws Exception {
        //获取加密对象
        Cipher cipher = Cipher.getInstance(transformation);
        //加密规则
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        //创建IV向量
        IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        //初始化加密模式和算法
        cipher.init(Cipher.ENCRYPT_MODE, sks,iv);
        //加密
        byte[] bytes = cipher.doFinal(input.getBytes());
        String encode = Base64.encode(bytes);
        return encode;
    }

    private static String decryptDES(String encryptDES, String key, String transformation, String algorithm) throws Exception {
        //获取加密对象
        Cipher cipher = Cipher.getInstance(transformation);
        //加密规则
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        //创建IV向量
        IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        //初始化加密模式和算法
        cipher. init(Cipher.DECRYPT_MODE, sks, iv);
        //加密
        byte[] bytes = cipher.doFinal(Base64.decode(encryptDES.getBytes()));
        return new String(bytes);
    }
}
